package com.beiding.jsonanalyzer.analyze.func.openfunc;

import com.beiding.jsonanalyzer.analyze.func.OneFunc;
import com.beiding.jsonanalyzer.analyze.func.base.EasyFunc;
import com.beiding.jsonanalyzer.analyze.func.base.OneFuncAdaptor;
import com.beiding.jsonanalyzer.utils.TextUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

/**
 * 日期格式化
 *
 * @author 丁常磊
 * @date 2022/5/19 11:23
 */

public class Join {


    public static OneFunc of(Object key, String by) {
        return FuncUtils.buildForEasyFunc(new OneFuncAdaptor<EasyFunc>() {
            @Override
            protected EasyFunc newInstance() {
                return new EasyFunc() {
                    @Override
                    protected Object execute(Object o) {
                        Collection collection = null;
                        if (o instanceof Collection) {
                            collection = (Collection) o;
                        } else if (o instanceof Object[]) {
                            collection = Arrays.asList((Object[]) o);
                        }
                        if (collection != null) {
                            StringBuilder builder = new StringBuilder();

                            Iterator iterator = collection.iterator();

                            if (iterator.hasNext()) {
                                builder.append(iterator.next());
                                while (iterator.hasNext()) {
                                    builder.append(by);
                                    builder.append(iterator.next());
                                }
                            }
                            return builder.toString();
                        }
                        return null;
                    }

                    @Override
                    public String toString() {
                        return "join(" + TextUtils.addFormat(core,"\t") + ",'" + by + "')";
                    }
                };
            }
        }, key);
    }

}
